package org.jeecg.modules.yusuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.hqbaoxiao.entity.HqBaoxiao;
import org.jeecg.modules.system.entity.SysCategory;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysCategoryMapper;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.workflow.dto.FlowData;
import org.jeecg.modules.workflow.dto.ProcessNode;
import org.jeecg.modules.workflow.service.IProcessEngine;
import org.jeecg.modules.workflow.utils.ProcessKit;
import org.jeecg.modules.yusuan.entity.CaiwuBiaozhun;
import org.jeecg.modules.yusuan.entity.CaiwuNz;
import org.jeecg.modules.yusuan.entity.NianDuHuiZong;
import org.jeecg.modules.yusuan.mapper.*;
import org.jeecg.modules.yusuan.service.ICaiwuBiaozhunService;
import org.jeecg.modules.yusuan.service.ICaiwuNzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: caiwu_yusuan
 * @Author: jeecg-boot
 * @Date:   2020-06-15
 * @Version: V1.0
 */
@Service
public class CaiwuNzServiceImpl extends ServiceImpl<CaiwuNzMapper, CaiwuNz> implements ICaiwuNzService {
    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private CaiwuNzMapper caiwuNzMapper;
    @Autowired
    private ICaiwuBiaozhunService caiwuBiaozhunService;
    @Autowired
    private IProcessEngine processEngine;

    @Override
    @Transactional(
            rollbackFor = {Exception.class}
    )
    public String startFlow(String recordId) {

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();


        String businesskey = recordId;
        identityservice.setAuthenticatedUserId(user.getUsername());
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", user.getUsername());
        Model modelData = repositoryService.getModel("2222505");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(user.getUsername()).singleResult();
        String processDefinitionId = task.getProcessDefinitionId();
        String currentNodeId = task.getTaskDefinitionKey();
        return task.getId();
    }

    public void startFlow2(CaiwuNz caiwuNz, FlowData flowData) {
        List<Map<String,Object>> dataList = flowData.getDataList();
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        Integer version = null;
        if(StringUtils.equals(caiwuNz.getJingfeiType(),"biaozhun")){
            CaiwuBiaozhun caiwuBiaozhun = caiwuBiaozhunService.getOne(new LambdaQueryWrapper<CaiwuBiaozhun>().eq(CaiwuBiaozhun::getDeptId,caiwuNz.getDeptId()).eq(CaiwuBiaozhun::getEffective,1).orderByDesc(CaiwuBiaozhun::getVersion).last("limit 1"));
            version = (caiwuBiaozhun== null || caiwuBiaozhun.getVersion() == null)?1:caiwuBiaozhun.getVersion()+1;
            List<CaiwuBiaozhun> list = new ArrayList<>();
            for(Map<String,Object> item:dataList){
                CaiwuBiaozhun biaozhun = (CaiwuBiaozhun) JsonUtils.toObject(JsonUtils.toJsonString(item),CaiwuBiaozhun.class);
                biaozhun.setVersion(version);
                biaozhun.setEffective(0);
                list.add(biaozhun);
            }
            caiwuBiaozhunService.saveOrUpdateBatch(list);
        }

        identityservice.setAuthenticatedUserId(user.getUsername());

//        Model modelData = repositoryService.getModel("2222505");
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();
//
//        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
//        String instanceid=instance.getId();
        caiwuNz.setProcessInstanceId(flowData.getProcessInstanceId());
        caiwuNz.setTaskId(flowData.getTaskId());
        caiwuNz.setVersion(version);
        caiwuNz.setProcessStatus(1);
        this.baseMapper.updateById(caiwuNz);
//        taskService.complete(task.getId(),variables);
        Map variables = new HashMap(){{
            put("auditUser",flowData.getNextUser());
        }};
        variables.put("status","1");
        variables.put("memo","");
        processEngine.submitTask(flowData,variables);
    }

    @Override
    public int jingfeiTypeCount(String deptId, String jingfeiType, Integer effective) {

        return this.caiwuNzMapper.jingfeiTypeCount(deptId,jingfeiType,effective);
    }

    @Override
    public IPage<CaiwuNz> myApplyList(Page<CaiwuNz> page, LoginUser user, CaiwuNz caiwuNz) {
        return this.baseMapper.myApplyList(page,user,caiwuNz);
    }

    @Override
    public IPage<CaiwuNz> myTodoTasks(Page<CaiwuNz> page, LoginUser user, CaiwuNz caiwuNz) {
        return this.baseMapper.myTodoTasks(page,user,caiwuNz);
    }

    @Override
    public IPage<CaiwuNz> myDoneTasks(Page<CaiwuNz> page, LoginUser user, CaiwuNz caiwuNz) {
        return this.baseMapper.myDoneTasks(page,user,caiwuNz);
    }

    @Override
    public void complateTask(LoginUser loginUser, FlowData flowData) {
        String memo = flowData.getComment();
        if(org.apache.commons.lang3.StringUtils.isBlank(memo)){
            memo = "1".equals(flowData.getAuditStatus())?"通过":"驳回";
            flowData.setComment(memo);
        }

        Map map = new HashMap(){{
            put("status",flowData.getAuditStatus());

        }};
        map.put("memo",memo);
        map.put("auditUser", flowData.getNextUser());
        taskService.addComment(flowData.getTaskId(),flowData.getProcessInstanceId(), JsonUtils.toJsonString(map));
        processEngine.submitTask(flowData,map);
//        taskService.complete(taskId,map);
    }

    @Override
    public void applyAgain(CaiwuNz caiwuNz, LoginUser user) {

    }
}
